import requests
import logging as log
import time
import browser_cookie3 as bcookie
from openpyxl import Workbook, load_workbook
from openpyxl.styles import *
import warnings

warnings.filterwarnings('ignore')
log.basicConfig(level=log.INFO)
import time
import math

reply_key = {
    "评论id": "rpid",
    "av号": "oid",
    "回复评论id": "root",
    "用户id": "mid",
    "用户昵称": "member.uname",
    "性别": "member.sex",
    "等级": "member.level_info.current_level",
    "评论": "content.message",
    "点赞数": "like",
    "up主点赞": "up_action.like",
    "up主回复": "up_action.reply"
}


def dict_query(dict_info, key):
    keys = key.split(".")
    value = dict_info.copy()
    for k in keys:
        value = value[k]
    return value


headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"
}


def bv_to_av(bv):
    url = "http://api.bilibili.com/x/web-interface/archive/stat?bvid=%s" % bv
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        return resp.json()['data']['aid']
    return ""


def av_to_bv(av):
    url = "http://api.bilibili.com/x/web-interface/archive/stat?aid=%s" % av
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        return resp.json()['data']['bvid']
    return ""


def get_reply_bak():
    # url = "https://api.bilibili.com/x/v2/reply/reply?csrf=8ee4e3d1471a7b16225480f95633e26d&oid=219590518&pn=1&ps=10&root=135292043600&type=1"
    url = "https://api.bilibili.com/x/v2/reply/reply?oid=219590518&pn=2&ps=10&root=135292043600&type=1"
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        log.info(resp.json())


def get_reply_total(av, reply_id, page_no, page_size=10, api_type=1):
    """
    获取楼层评论总页数
    :param av
    :param reply_id
    :page_no 页数
    :page_size 每页显示条数
    :api_type 类型
    """
    url = "https://api.bilibili.com/x/v2/reply/reply?oid=%s&pn=%s&ps=%s&root=%s&type=%s" % (
        av, page_no, page_size, reply_id, api_type)
    log.info(url)
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        # 数据
        data = resp.json()["data"]
        # 总条数
        count = data["page"]["count"]
        # 当前页
        num = data["page"]["num"]
        # 每页条数
        size = data["page"]["size"]
        # 总页数
        total = math.ceil(int(count) / int(size))
        log.info("总条数:%s,当前页:%s,每页条数:%s" % (count, num, size))
        return count, num, size, total
    return None, None, None, None


def get_reply(av, reply_id, page_no, page_size=10, api_type=1):
    """
    获取楼层评论
    :param av
    :param reply_id
    :page_no 页数
    :page_size 每页显示条数
    :api_type 类型
    """
    url = "https://api.bilibili.com/x/v2/reply/reply?oid=%s&pn=%s&ps=%s&root=%s&type=%s" % (
        av, page_no, page_size, reply_id, api_type)
    resp = requests.get(url, headers=headers)
    reply_data = []
    if resp.status_code == 200:
        # 数据
        replies = resp.json()["data"]["replies"]
        columns = ["用户id", "用户昵称", "性别", "等级", "性别", "消息", "点赞数", "up主点赞", "up主回复"]
        for reply in replies:
            data = []
            for column in columns:
                data.append(dict_query(reply, reply_key[column]))
            reply_data.append(data)
    return reply_data


def get_comment(av, page):
    url = "https://api.bilibili.com/x/v2/reply/main?next=%s&type=1&oid=%s&mode=3" % (
        page, av)
    log.info(url)
    resp = requests.get(url, headers=headers)
    if resp.status_code == 200:
        replies = resp.json()["data"]["replies"]
        for reply in replies:
            member_info = reply["member"]
            # 用户id
            mid = member_info["mid"]
            # 用户昵称
            uname = member_info["uname"]
            # 性别
            sex = member_info["sex"]
            # 当前等级
            current_level = member_info["level_info"]["current_level"]
            # 消息
            message = reply["content"]["message"]
            # 点赞
            like = reply["like"]
            # up主点赞
            reply["up_action"]["like"]
            # up主回复
            reply["up_action"]["reply"]

            log.info("用户id:%s,用户昵称:%s,用户性别:%s,用户等级:%s,用户评论:%s" %
                     (mid, uname, sex, current_level, message))


def get_cookie():
    # cc = bcookie.chrome(domain_name="www.bilibili.com")
    # log.info(cc)
    # #requests.get("http://www.bilibili.com",)
    cc = bcookie.chrome(domain_name="www.bilibili.com")
    log.info(cc)
    for cookie in cc:
        log.info("name:%s,value:%s" % (cookie.name, cookie.value))


def reply_process():
    # 获取总条数
    av = "219590518"
    reply_id = "135292043600"
    count, num, size, total = get_reply_total(av, reply_id, 1, 10, 1)
    data = []
    data.append(["用户id", "用户昵称", "性别", "等级", "性别", "消息", "点赞数", "up主点赞", "up主回复"])
    for page_no in range(1, 2):
        log.info("当前页:%s" % page_no)
        data_list = get_reply(av, reply_id, page_no, size, 1)
        time.sleep(3)
        for item in data_list:
            data.append(item)
    wb = Workbook()
    ws = wb.active
    ws.title = "%s回复" % reply_id
    for item in data:
        ws.append(item)
    wb.save("D:\\b站\\%s_%s.xlsx" % (av, reply_id))


if __name__ == "__main__":
    # BV1sP4113729
    av = bv_to_av("BV1o14y1E7xG")
    log.info("av:%s" % av)
    # bv = av_to_bv(av)
    # log.info("bv:%s" % bv)
    # for index in range(1,3):
    #     get_comment(av, index)
    #     time.sleep(3)
    # get_cookie()
    # get_reply("219590518", "135292043600",1, 10, 1)
    reply_process()
